package com.nanxhs;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 选择排序
 * @author: haibin.tang
 * @date: 2021/2/8
 */
public class SelectionSort {
    /**
     * 找出列表中最小的数值所在的索引位置
     * @param list
     * @return 最小数值索引位置
     */
    private static int getMinNumberIndex(List<Integer> list) {
        int minIndex = -1;
        int minData = -1;
        for (int index = 0; index < list.size(); ++index) {
            if (index == 0) {
                minIndex = index;
                minData = list.get(index);
                continue;
            }
            Integer currentData = list.get(index);
            if (currentData < minData) {
                minIndex = index;
                minData = list.get(index);
            }
        }
        return minIndex;
    }

    /**
     * 排序<br/>
     * 找出数组中最小的数值，然后把最小数值存入新的列表中，然后把最小的数值从原列表中移除， 重复之前的步骤直到原列表没有元素
     * @param list
     * @return 排序后的列表
     */
    public static List<Integer> sort(List<Integer> list) {
        List<Integer> result = new ArrayList<>(list.size());
        while (list.size() > 0) {
            int minNumberIndex = getMinNumberIndex(list);
            result.add(list.get(minNumberIndex));
            list.remove(minNumberIndex);
        }
        return result;
    }

    public static void main(String[] args) {
        List<Integer> dataList = new ArrayList<>(Arrays.asList(10, 25, 81, 1, 25, 36, 18, -1, 4, 6, 87, 21, 36, 15));
        System.out.println(dataList);
        System.out.println(sort(dataList));
    }
}
